import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public class test2{
    private JFrame frame;
    private JTextField projectNameField;
    private JTextField addNameField;  // 新增奖项用姓名输入
    private JTextField queryNameField;  // 查询用姓名输入
    private JTable awardTable;
    private DefaultTableModel mainTableModel;  // 存储所有记录的模型
    private DefaultTableModel currentModel;    // 当前显示的模型（全部/个人）
    private JLabel statusLabel;  // 表格状态提示
    private JLabel totalScoreLabel;  // 总分提示

    private List<Award> awardList = new ArrayList<>();
    private Map<String, Double> studentTotalScores = new HashMap<>();

    // 贡献度量化表（每行和为1）
    private final double[][] contributionTable = {
            {1.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00},
            {0.65, 0.35, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00},
            {0.50, 0.25, 0.20, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00},
            {0.50, 0.25, 0.15, 0.10, 0.05, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00},
            {0.50, 0.25, 0.10, 0.10, 0.05, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00},
            {0.45, 0.20, 0.10, 0.10, 0.10, 0.05, 0.00, 0.00, 0.00, 0.00, 0.00},
            {0.40, 0.20, 0.10, 0.10, 0.10, 0.05, 0.05, 0.00, 0.00, 0.00, 0.00},
            {0.38, 0.20, 0.10, 0.10, 0.10, 0.05, 0.05, 0.02, 0.00, 0.00, 0.00},
            {0.38, 0.20, 0.10, 0.10, 0.10, 0.05, 0.05, 0.01, 0.01, 0.00, 0.00},
            {0.38, 0.20, 0.10, 0.10, 0.10, 0.05, 0.04, 0.01, 0.01, 0.01, 0.00},
            {0.38, 0.20, 0.10, 0.10, 0.10, 0.04, 0.04, 0.01, 0.01, 0.01, 0.01}
    };

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> new test2().initUI());
    }

    private void initUI() {
        frame = new JFrame("学科竞赛加分计算器");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(1100, 650);
        frame.setLocationRelativeTo(null);
        frame.setLayout(new BorderLayout(10, 10));

        // 1. 顶部输入面板
        JPanel inputPanel = new JPanel(new GridLayout(4, 4, 10, 10));
        inputPanel.setBorder(BorderFactory.createTitledBorder("请输入奖项信息"));  // 标题提示
        // Deleted:inputPanel.setMargin(new Insets(10, 10, 10, 10));
        inputPanel.setBorder(BorderFactory.createCompoundBorder(
                BorderFactory.createTitledBorder("请输入奖项信息"),
                BorderFactory.createEmptyBorder(10, 10, 10, 10)
        ));
        
        // 新增奖项区域
        inputPanel.add(new JLabel("项目名称:"));
        projectNameField = new JTextField();
        inputPanel.add(projectNameField);

        inputPanel.add(new JLabel("学生姓名:"));
        addNameField = new JTextField();
        inputPanel.add(addNameField);

        // 奖项类别
        inputPanel.add(new JLabel("奖项大类:"));
        JPanel classPanel = new JPanel();
        JRadioButton aClass = new JRadioButton("A类");
        JRadioButton bClass = new JRadioButton("B类");
        JRadioButton cClass = new JRadioButton("C类");
        ButtonGroup classGroup = new ButtonGroup();
        classGroup.add(aClass);
        classGroup.add(bClass);
        classGroup.add(cClass);
        classPanel.add(aClass);
        classPanel.add(bClass);
        classPanel.add(cClass);
        inputPanel.add(classPanel);

        // 奖项级别
        inputPanel.add(new JLabel("奖项级别:"));
        JPanel levelPanel = new JPanel();
        JRadioButton national = new JRadioButton("国家级");
        JRadioButton provincial = new JRadioButton("省部级");
        ButtonGroup levelGroup = new ButtonGroup();
        levelGroup.add(national);
        levelGroup.add(provincial);
        levelPanel.add(national);
        levelPanel.add(provincial);
        inputPanel.add(levelPanel);

        // 奖项等次
        inputPanel.add(new JLabel("奖项等次:"));
        JPanel prizePanel = new JPanel();
        JRadioButton first = new JRadioButton("一等奖");
        JRadioButton second = new JRadioButton("二等奖");
        JRadioButton third = new JRadioButton("三等奖");
        ButtonGroup prizeGroup = new ButtonGroup();
        prizeGroup.add(first);
        prizeGroup.add(second);
        prizeGroup.add(third);
        prizePanel.add(first);
        prizePanel.add(second);
        prizePanel.add(third);
        inputPanel.add(prizePanel);

        // 个人排名
        inputPanel.add(new JLabel("个人排名:"));
        JComboBox<Integer> rankCombo = new JComboBox<>(new Integer[]{1,2,3,4,5,6,7,8,9,10,11});
        inputPanel.add(rankCombo);

        // 查询区域
        inputPanel.add(new JLabel("查询姓名:"));
        queryNameField = new JTextField();
        inputPanel.add(queryNameField);

        // 合作人数
        inputPanel.add(new JLabel("合作人数:"));
        JComboBox<Integer> teamCombo = new JComboBox<>(new Integer[]{1,2,3,4,5,6,7,8,9,10,11});
        inputPanel.add(teamCombo);

        frame.add(inputPanel, BorderLayout.NORTH);

        // 2. 中间表格区域（带状态提示和控制按钮）
        JPanel tablePanel = new JPanel(new BorderLayout());

        // 表格上方：状态提示+返回按钮
        JPanel tableTopPanel = new JPanel(new BorderLayout());
        statusLabel = new JLabel("当前显示所有学生的奖项记录", SwingConstants.LEFT);
        statusLabel.setFont(new Font("宋体", Font.PLAIN, 14));
        statusLabel.setForeground(Color.DARK_GRAY);
        statusLabel.setBorder(BorderFactory.createEmptyBorder(5, 10, 5, 10));

        // 返回全部记录按钮（默认隐藏，查询时显示）
        JButton backBtn = new JButton("返回全部记录");
        backBtn.setVisible(false);
        backBtn.addActionListener(e -> {
            // 切换回全部记录
            awardTable.setModel(mainTableModel);
            currentModel = mainTableModel;
            statusLabel.setText("当前显示所有学生的奖项记录");
            statusLabel.setForeground(Color.DARK_GRAY);
            backBtn.setVisible(false); // 隐藏返回按钮
            totalScoreLabel.setText("请查询学生总分");
        });

        tableTopPanel.add(statusLabel, BorderLayout.WEST);
        tableTopPanel.add(backBtn, BorderLayout.EAST);
        tablePanel.add(tableTopPanel, BorderLayout.NORTH);

        // 表格（行首增加"学生姓名"列）
        String[] columns = {"学生姓名", "项目名称", "奖项大类", "奖项级别", "奖项等次", "个人排名", "合作人数", "单项加分"};
        mainTableModel = new DefaultTableModel(columns, 0);
        currentModel = mainTableModel; // 默认显示全部记录
        awardTable = new JTable(mainTableModel);
        // 设置第一列（学生姓名）居左显示，便于识别
        awardTable.getColumnModel().getColumn(0).setPreferredWidth(100);
        JScrollPane scrollPane = new JScrollPane(awardTable);
        scrollPane.setBorder(BorderFactory.createTitledBorder("奖项记录列表（行首为学生姓名）"));
        tablePanel.add(scrollPane, BorderLayout.CENTER);

        frame.add(tablePanel, BorderLayout.CENTER);

        // 3. 底部按钮区域
        JPanel bottomPanel = new JPanel(new BorderLayout(20, 10));
        bottomPanel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));

        // 新增奖项按钮
        JButton addBtn = new JButton("新增奖项");
        addBtn.addActionListener(e -> {
            String project = projectNameField.getText().trim();
            String name = addNameField.getText().trim();
            String cls = aClass.isSelected() ? "A类" : (bClass.isSelected() ? "B类" : "C类");
            String level = national.isSelected() ? "国家级" : "省部级";
            String prize = first.isSelected() ? "一等奖" : (second.isSelected() ? "二等奖" : "三等奖");
            int rank = (Integer) rankCombo.getSelectedItem();
            int team = (Integer) teamCombo.getSelectedItem();

            if (project.isEmpty() || name.isEmpty()) {
                JOptionPane.showMessageDialog(frame, "项目名称和学生姓名不能为空！", "输入错误", JOptionPane.ERROR_MESSAGE);
                return;
            }
            addAward(project, name, cls, level, prize, rank, team);
        });

        // 查询按钮
        JButton queryBtn = new JButton("查询个人总分");
        queryBtn.addActionListener(e -> {
            String name = queryNameField.getText().trim();
            if (name.isEmpty()) {
                JOptionPane.showMessageDialog(frame, "请输入要查询的学生姓名！", "输入错误", JOptionPane.ERROR_MESSAGE);
                return;
            }
            // 查询时显示返回按钮
            backBtn.setVisible(true);
            queryScores(name);
        });

        // 总分提示
        totalScoreLabel = new JLabel("请查询学生总分", SwingConstants.RIGHT);
        totalScoreLabel.setFont(new Font("宋体", Font.BOLD, 16));
        totalScoreLabel.setForeground(Color.RED);

        bottomPanel.add(addBtn, BorderLayout.WEST);
        bottomPanel.add(queryBtn, BorderLayout.CENTER);
        bottomPanel.add(totalScoreLabel, BorderLayout.EAST);

        frame.add(bottomPanel, BorderLayout.SOUTH);

        frame.setVisible(true);
    }

    // 新增奖项（行首添加学生姓名）
    private void addAward(String project, String name, String cls, String level, String prize, int rank, int team) {
        // 计算加分
        double base = getBaseScore(cls, level, prize);
        if (base < 0) {
            JOptionPane.showMessageDialog(frame, "提示：C类省部级三等奖不加分", "加分规则", JOptionPane.INFORMATION_MESSAGE);
            return;
        }
        double contribution = getContribution(rank, team);
        double score = Math.round(base * contribution * 100.0) / 100.0;

        // 保存记录（行首增加学生姓名）
        Award award = new Award(project, cls, level, prize, rank, team, score, name);
        awardList.add(award);
        mainTableModel.addRow(new Object[]{
                name, project, cls, level, prize, rank, team, score
        });

        // 更新总分缓存
        studentTotalScores.put(name, studentTotalScores.getOrDefault(name, 0.0) + score);

        // 提示新增成功
        JOptionPane.showMessageDialog(frame,
                String.format("%s的「%s」奖项已添加，单项加分：%.2f分", name, project, score),
                "添加成功", JOptionPane.INFORMATION_MESSAGE);

        // 清空输入框
        projectNameField.setText("");
        addNameField.setText("");
    }

    // 查询个人分数
    private void queryScores(String name) {
        // 筛选个人记录
        List<Award> personalAwards = awardList.stream()
                .filter(a -> a.studentName.equals(name))
                .collect(Collectors.toList());

        // 1. 更新表格状态提示
        if (personalAwards.isEmpty()) {
            statusLabel.setText(String.format("当前显示「%s」的查询结果：无记录", name));
            statusLabel.setForeground(Color.ORANGE);
        } else {
            statusLabel.setText(String.format("当前显示「%s」的所有奖项记录（共%d条）", name, personalAwards.size()));
            statusLabel.setForeground(new Color(0, 128, 0));
        }

        // 2. 更新表格数据（行首显示学生姓名）
        DefaultTableModel queryModel = new DefaultTableModel(
                new String[]{"学生姓名", "项目名称", "奖项大类", "奖项级别", "奖项等次", "个人排名", "合作人数", "单项加分"}, 0);
        for (Award a : personalAwards) {
            queryModel.addRow(new Object[]{
                    a.studentName, a.project, a.cls, a.level, a.prize, a.rank, a.team, a.score
            });
        }
        awardTable.setModel(queryModel);
        currentModel = queryModel;

        // 3. 显示总分
        double total = studentTotalScores.getOrDefault(name, 0.0);
        double effective = Math.min(total, 2.5);
        if (personalAwards.isEmpty()) {
            totalScoreLabel.setText(String.format("%s 暂无奖项记录，总分为0分", name));
            JOptionPane.showMessageDialog(frame,
                    String.format("查询结果：\n%s 暂无任何奖项记录\n总分为：0分", name),
                    "查询完成", JOptionPane.INFORMATION_MESSAGE);
        } else {
            totalScoreLabel.setText(
                    String.format("%s 的总分为：%.2f分（有效分：%.2f分）", name, total, effective)
            );
            JOptionPane.showMessageDialog(frame,
                    String.format("查询结果：\n%s 的总加分：%.2f分\n（有效分：%.2f分）\n共%d条记录",
                            name, total, effective, personalAwards.size()),
                    "查询完成", JOptionPane.INFORMATION_MESSAGE);
        }
    }

    // 基础分计算
    private double getBaseScore(String cls, String level, String prize) {
        if ("A类".equals(cls)) {
            if ("国家级".equals(level)) {
                return "一等奖".equals(prize) ? 2.5 : ("二等奖".equals(prize) ? 2 : 1.5);
            } else {
                return "一等奖".equals(prize) ? 2 : ("二等奖".equals(prize) ? 1.5 : 1);
            }
        } else if ("B类".equals(cls)) {
            if ("国家级".equals(level)) {
                return "一等奖".equals(prize) ? 2 : ("二等奖".equals(prize) ? 1.5 : 1);
            } else {
                return "一等奖".equals(prize) ? 1.5 : ("二等奖".equals(prize) ? 1 : 0.5);
            }
        } else { // C类
            if ("国家级".equals(level)) {
                return "一等奖".equals(prize) ? 1.5 : ("二等奖".equals(prize) ? 1 : 0.5);
            } else {
                return "三等奖".equals(prize) ? -1 : ("一等奖".equals(prize) ? 1 : 0.5);
            }
        }
    }

    // 贡献度计算
    private double getContribution(int rank, int team) {
        if (team < 1 || team > 11 || rank < 1 || rank > team) return 0.0;
        return contributionTable[team - 1][rank - 1];
    }

    // 奖项实体类
    private class Award {
        String project, cls, level, prize, studentName;
        int rank, team;
        double score;

        Award(String project, String cls, String level, String prize, int rank, int team, double score, String studentName) {
            this.project = project;
            this.cls = cls;
            this.level = level;
            this.prize = prize;
            this.rank = rank;
            this.team = team;
            this.score = score;
            this.studentName = studentName;
        }
    }
}